package com.tju.backend.oauth.config.jwt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * Token管理方式配置
 *
 * @Author CLS
 * @Date 2021/12/30 14:49
 */
@Configuration
public class TokenConfig {

    @Autowired //采用redis管理token
    private RedisConnectionFactory redisConnectionFactory;

    // JWT 签名秘钥
    private static final String SIGNING_KEY = "mengxuegu-key";

    @Bean
    public TokenStore tokenStore() {
        // redis 管理令牌
        return new RedisTokenStore(redisConnectionFactory);
    }


    @Bean // 在 JwtAccessTokenConverter 中定义 Jwt 签名密码
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        // 对称密钥来签署我们的令牌，资源服务器也将使用此秘钥来验证准码性
        converter.setSigningKey(SIGNING_KEY);
        return converter;
    }


    /**
     * 引入自定义JWTokenEnhancer:
     * 自定义JWTokenEnhancer实现TokenEnhancer并重写enhance方法,将附加信息加入oAuth2AccessToken中
     *
     * @return
     */
    @Bean
    public TokenEnhancer jwtTokenEnhancer() {
        return new JWTokenEnhancer();
    }
}
